package com.ruoyi.write.controller;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;

import com.ruoyi.essay.domain.Essay;
import com.ruoyi.essay.service.IEssayService;
import com.ruoyi.websocket.apiRequest;
import com.ruoyi.write.domain.Paper;
import com.volcengine.ark.runtime.model.completion.chat.ChatMessage;
import com.volcengine.ark.runtime.model.completion.chat.ChatMessageRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @author wen
 */
@RestController
@RequestMapping("/write")
public class PaperController {

    @Autowired
    private IEssayService essayService;

    /**
     * 论文生成
     * @param request 论文要求
     * @return AjaxResult 结果类
     */
    @PostMapping("/paper")
    public AjaxResult paper(@RequestBody Paper request) {
        System.out.println(request);
        List<ChatMessage> messageList = new ArrayList<>();
        String add;
        String endMessage = "";
        String message = "假设你的受教育程度为" + request.getEducationLevel() + "，";
        message += "你需要写出一篇论文的某一部分"+"，题目为" + request.getTitle()+ "，";
        message += "主题描述为" + request.getTopicDescription()+";";
        String[] arr = request.getOutlineSections().toArray(new String[0]);
        int length = 0;
        for (String s : arr) {
            if (!s.isEmpty()) {
                length++;
                if (length==1) {
                    add = "现在请你写出这篇论文的" + s + "部分，尽可能详细，权威，紧贴时代背景，字数要求100字，只生成这一部分的内容，呈现生成部分的标题，不用总结";
                }else {
                    add = "现在请你再写出这篇论文的" + s + "部分，尽可能详细，权威，紧贴时代背景，尽量不要分点答，字数要求100字以上，不用总结之前生成的，我已经保存，呈现生成部分的标题，内容与上文连贯";
                }
                String question = message + add;
                System.out.println(question);
                messageList.add(ChatMessage.builder().role(ChatMessageRole.USER).content(question).build());
                endMessage += apiRequest.request(messageList);
            }
        }

        System.out.println(endMessage);
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = loginUser.getUser();
        Long userId = user.getUserId();
        Essay essay = new Essay();
        essay.setUserId(userId);
        essay.setContent(endMessage);
        essay.setTitle(request.getTitle());
        essay.setFontSize(request.getFontSize());
        essay.setHeadingSize(request.getHeadingSize());
        essay.setLineHeight(request.getLineHeight());
        essay.setIndentation(request.getIndentation());
        essayService.insertEssay(essay);
        return AjaxResult.success(essay);
    }
}
